package com.aca.market.util;

import lombok.*;

@AllArgsConstructor
@NoArgsConstructor
@Data
@ToString
public class PageUtil {



    // 当前页码
//    private Long current = 1;
    private Long current;
    // 显示上限
//    private Long limit = 10;
    private Long limit;
    // 数据总数(用于计算总页数)
    private Long rows;
    // 查询路径(用于复用分页链接)
    private String path;

    public PageUtil(Long current, Long limit, Long rows) {
        this.current = current;
        this.limit = limit;
        this.rows = rows;
    }

    public PageUtil(Long limit, Long rows, String path) {
        this.limit = limit;
        this.rows = rows;
        this.path = path;
    }

    public Long getCurrent() {
        return current;
    }

    public void setCurrent(Long current) {
        if (current >= 1) {
            this.current = current;
        }
    }

    public Long getLimit() {
        return limit;
    }

    public void setLimit(Long limit) {
        if (limit >= 1 && limit <= 100) {
            this.limit = limit;
        }
    }

    public Long getRows() {
        return rows;
    }

    public void setRows(Long rows) {
        if (rows >= 0) {
            this.rows = rows;
        }
    }

    public String getPath() {
        return path;
    }

    public void setPath(String path) {
        this.path = path;
    }

    /**
     * 获取当前页的起始行
     *
     * @return
     */
    public Long getOffset() {
        // current * limit - limit
        return (current - 1) * limit;
    }

    /**
     * 获取总页数
     *
     * @return
     */
    public Long getTotal() {
        // rows / limit [+1]
        if (rows % limit == 0) {
            return rows / limit;
        } else {
            return rows / limit + 1;
        }
    }

    /**
     * 获取起始页码
     *
     * @return
     */
    public Long getFrom() {
        Long from = current - 2;
        return from < 1 ? 1 : from;
    }

    /**
     * 获取结束页码
     *
     * @return
     */
    public Long getTo() {
        Long to = current + 2;
        Long total = getTotal();
        return to > total ? total : to;
    }

}
